package itbour.onetouchshow.activity.challengezone.video;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import VideoHandle.EpEditor;
import VideoHandle.EpVideo;
import VideoHandle.OnEditorListener;
import itbour.onetouchshow.AppCache;
import itbour.onetouchshow.R;
import itbour.onetouchshow.base.mvp.MVPBaseActivity;
import itbour.onetouchshow.bean.CameraSizeBean;
import itbour.onetouchshow.bean.VideoSizeConfigBean;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.utils.DisplayUtil;
import itbour.onetouchshow.utils.T_;
import itbour.onetouchshow.widget.VerticalVideoRecordProgress;
import itbour.onetouchshow.widget.VideoRecordProgress;

/**
 * Created by guoh on 2018/7/6.
 * 功能描述：视频录制页面
 * 需要的参数：视频的宽高比配置信息 最大可录制时长
 */
public class VideoRecordActivity extends MVPBaseActivity {

    private VideoSizeConfigBean configBean;
    private SurfaceView mSurfaceView;
    private ImageView mImgStartRecord;
    private TextView mTvReRecord;
    private TextView mTvChoose;
    private ImageView mImgBack;
    private ImageView mImgNineToSixteenBack;
    private View mTopLayer;
    private View mBottomLayer;
    private VideoRecordProgress recordProgress;
    private VerticalVideoRecordProgress verticalRecordProgress;
    //是否正在录像
    private boolean mStartedFlg = false;
    //多媒体录音
    private MediaRecorder mRecorder;
    //相机
    private Camera mCamera;
    //视频保存路径
    private String outputPath;
    private SurfaceHolder mSurfaceHolder;
    //true 9:16 false 16:9
    private boolean isNormalNineToSixteen;
    //获取的系统支持的输出大小
    private Camera.Size videoSize;
    //当前录制的时间 秒
    private int recordSeconds = -1;
    //最小录制时间 秒
    private int minRecordSeconds = 3;
    //最大录制时间
    private int maxRecordSeconds;
    //文件输出路径
    private String cachePath = AppCache.getInstance().VIDEO_SAVE_DIR;
    //计时
    private Handler timeHandler;
    //加载框是否显示
    private boolean isShowProgress = false;
    private Runnable timeRunnable = new Runnable() {
        @Override
        public void run() {
            recordSeconds += 1;
            if (recordSeconds == maxRecordSeconds) {
                //到达最大录制时间
                completeStopRecord();
            } else {
                timeHandler.postDelayed(this, 1000);
            }
            if (recordProgress.getVisibility() == View.VISIBLE) {
                recordProgress.setProgress(recordSeconds);
            }
            if (verticalRecordProgress.getVisibility() == View.VISIBLE) {
                verticalRecordProgress.setProgress(recordSeconds);
            }


        }
    };
    private MediaRecorder.OnErrorListener OnErrorListener = new MediaRecorder.OnErrorListener() {
        @Override
        public void onError(MediaRecorder mediaRecorder, int what, int extra) {
            try {
                if (mediaRecorder != null) {
                    mediaRecorder.reset();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    public static Intent getLaunchIntent(Context context, VideoSizeConfigBean videoSize, int maxRecordSeconds) {
        Intent intent = new Intent(context, VideoRecordActivity.class);
        intent.putExtra(AppConst.KEY_VIDEO_SIZE_CONFIG, videoSize);
        intent.putExtra(AppConst.KEY_VIDEO_RECORD_MAX_SECONDS, maxRecordSeconds);
        return intent;
    }

    @Override
    protected int getLayoutId() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        return R.layout.ac_video_record_system;

    }

    @Override
    protected void afterCreate(Bundle bundle) {
        configBean = (VideoSizeConfigBean) getIntent().getSerializableExtra(AppConst.KEY_VIDEO_SIZE_CONFIG);
        initViews();
        initDatas();
        addListeners();
    }

    private void initViews() {
        mSurfaceView = findViewById(R.id.surfaceview);
        mImgStartRecord = findViewById(R.id.iv_start_image);
        mTvChoose = findViewById(R.id.tv_choose);
        mTvReRecord = findViewById(R.id.tv_re_record);
        mImgBack = findViewById(R.id.iv_back);
        mTopLayer = findViewById(R.id.view_top_layer);
        mBottomLayer = findViewById(R.id.view_bottom_layer);
        mImgNineToSixteenBack = findViewById(R.id.iv_back_nine_to_sixteen);
        recordProgress = findViewById(R.id.record_progress);
        verticalRecordProgress = findViewById(R.id.vertical_record_progress);
    }

    private void initDatas() {
        ((AudioManager) getSystemService(Context.AUDIO_SERVICE)).setStreamMute(AudioManager.STREAM_SYSTEM, true);
        maxRecordSeconds = getIntent().getIntExtra(AppConst.KEY_VIDEO_RECORD_MAX_SECONDS, 60);
        timeHandler = new Handler();
        setSurfaceViewHeight();
        mSurfaceHolder = mSurfaceView.getHolder();
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);//缓冲区
        mSurfaceHolder.setFixedSize(mSurfaceView.getWidth(), mSurfaceView.getHeight());
        mSurfaceHolder.setKeepScreenOn(true);
        mSurfaceHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                initCamera();
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                if (mSurfaceHolder.getSurface() == null) {
                    return;
                }
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                releaseCamera();
            }
        });
    }

    private void addListeners() {
        mImgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                releaseRecordAndCamera();
                finish();
            }
        });
        mImgNineToSixteenBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                releaseRecordAndCamera();
                finish();
            }
        });
        mTvReRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resetProgress();
                initCamera();
                mTvChoose.setVisibility(View.GONE);
                mTvReRecord.setVisibility(View.GONE);
                mImgStartRecord.setBackground(VideoRecordActivity.this.getResources().getDrawable(R.mipmap.icon_video_record_start));
                mImgStartRecord.setEnabled(true);
            }
        });

        mImgStartRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //开始录制视频
                if (!mStartedFlg) {
                    if (!startRecord()) {
                        return;
                    }
                    //录像开始
                    mStartedFlg = true;
                    mImgStartRecord.setBackground(VideoRecordActivity.this.getResources().getDrawable(R.mipmap.icon_video_record_pause));
                    mTvChoose.setVisibility(View.GONE);
                    mTvReRecord.setVisibility(View.GONE);
                    timeHandler.post(timeRunnable);
                } else {
                    //停止录制视频
                    if (recordSeconds < minRecordSeconds) {
                        T_.showCustomToast("录制视频时长过短");
                        return;
                    }
                    completeStopRecord();
                }
            }
        });

        mTvChoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (recordSeconds < minRecordSeconds) {
                    T_.showCustomToast("录制视频时长过短");
                    return;
                }
                File file = new File(outputPath);
                if (file.length() == 0) {
                    T_.showCustomToast("权限被拒绝或其它原因导致视频录制出错,请重录");
                    return;
                }
                if (mTopLayer.getVisibility() == View.VISIBLE) {
                    //1:1视频走裁剪720*720逻辑
                    EpVideo epVideo = new EpVideo(outputPath);
                    epVideo.crop(720, 720, 0, 160);
                    String mOutPutPath = cachePath + File.separator + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".mp4";
                    EpEditor.OutputOption option = new EpEditor.OutputOption(mOutPutPath);
                    option.bitRate = 4;
                    EpEditor.exec(epVideo, option, new OnEditorListener() {
                        @Override
                        public void onSuccess() {
                            timeHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    isShowProgress = false;
                                    dismissProgressDialog();
                                    Intent intent = new Intent();
                                    intent.putExtra(AppConst.KEY_RECORD_VIDEO_PATH, mOutPutPath);
                                    setResult(RESULT_OK, intent);
                                    finish();
                                }
                            });

                        }

                        @Override
                        public void onFailure() {

                        }

                        @Override
                        public void onProgress(float progress) {
                            timeHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    if (!isShowProgress) {
                                        showProgressDialogWithText("视频合成中...");
                                        isShowProgress = true;
                                    }
                                }
                            });

                        }
                    });
                } else {
                    Intent intent = new Intent();
                    intent.putExtra(AppConst.KEY_RECORD_VIDEO_PATH, outputPath);
                    setResult(RESULT_OK, intent);
                    finish();
                }

            }
        });
    }

    //根据16:9 或9:16设置UI样式
    private void setUiOrientation() {
        if (!isNormalNineToSixteen) {
            mTvReRecord.setRotation(90);
            mTvChoose.setRotation(90);

            recordProgress.setVisibility(View.GONE);
            verticalRecordProgress.setVisibility(View.VISIBLE);
            verticalRecordProgress.setTotalCount(maxRecordSeconds);
            verticalRecordProgress.setProgress(recordSeconds);
        } else {
            recordProgress.setVisibility(View.VISIBLE);
            verticalRecordProgress.setVisibility(View.GONE);
            recordProgress.setTotalCount(maxRecordSeconds);
            recordProgress.setProgress(recordSeconds);
        }
    }

    //根据预览比例设置SurfaceView大小
    private void setSurfaceViewHeight() {
        String ratio = configBean.getVideoSize();
        String[] array = ratio.split(":");
        //ex   1:1
        if (array != null && array[0].equals("9") && array[1].equals("16") || (array != null && array[0].equals("1") && array[1].equals("1"))) {
            //竖屏
            isNormalNineToSixteen = true;
            mImgBack.setVisibility(View.VISIBLE);
            mImgNineToSixteenBack.setVisibility(View.GONE);
        } else {
            isNormalNineToSixteen = false;
            mImgNineToSixteenBack.setVisibility(View.VISIBLE);
            mImgBack.setVisibility(View.GONE);
        }
        if (isNormalNineToSixteen && !array[0].equals(array[1])) {
            array = new String[]{"16", "9"};
        }
        float scale = Float.parseFloat(array[0]) / Float.parseFloat(array[1]);
        int screenHeight = DisplayUtil.getScreenDispaly(VideoRecordActivity.this)[1];
        int screenWidth = DisplayUtil.getScreenDispaly(VideoRecordActivity.this)[0];
        if (scale == 1) {
            //1:1设置自定义蒙层
            mTopLayer.setVisibility(View.VISIBLE);
            RelativeLayout.LayoutParams bottomLayerParams = (RelativeLayout.LayoutParams) mBottomLayer.getLayoutParams();
            bottomLayerParams.height = screenHeight - screenWidth - DisplayUtil.dip2px(VideoRecordActivity.this, 80);
            mBottomLayer.setLayoutParams(bottomLayerParams);
        }
    }

    //初始化摄像头
    private void initCamera() {
        if (mCamera != null) {
            releaseCamera();
        }
        try {
            mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
        } catch (Exception e) {

        }
        if (mCamera == null) {
            Toast.makeText(VideoRecordActivity.this, "未能获取到相机", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        try {
            //将相机与SurfaceHolder绑定
            mCamera.setPreviewDisplay(mSurfaceHolder);
            //配置CameraParams
            configCameraParams();
            //启动相机预览
            mCamera.startPreview();
        } catch (IOException e) {
            Log.d("TAG", "Error starting camera preview: " + e.getMessage());
        }
    }

    //配置摄像头参数
    private void configCameraParams() {
        Camera.Parameters params = mCamera.getParameters();
        //设置最佳预览分辨率
        Camera.Size preSize = getCloselyPreSize(true, mSurfaceView.getWidth(), mSurfaceView.getHeight(), params.getSupportedPreviewSizes());
        params.setPreviewSize(preSize.width, preSize.height);
        videoSize = getCloselyVideoSize(true, mSurfaceView.getWidth(), mSurfaceView.getHeight(), params.getSupportedVideoSizes());
        mCamera.setParameters(params);

        //设置相机的横竖屏(竖屏需要旋转90°)
        if (VideoRecordActivity.this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
            params.set("orientation", "portrait");
            mCamera.setDisplayOrientation(90);
        } else {
            params.set("orientation", "landscape");
            mCamera.setDisplayOrientation(0);
        }
        //设置聚焦模式
        params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
        //缩短Recording启动时间
        params.setRecordingHint(true);
        //影像稳定能力
//        if (params.isVideoStabilizationSupported())
//            params.setVideoStabilization(true);
        mCamera.setParameters(params);
    }

    //配置录像参数
    private void configMediaRecorder(int width, int height) {
        mRecorder = new MediaRecorder();
        mRecorder.reset();
        mRecorder.setCamera(mCamera);
        mRecorder.setOnErrorListener(OnErrorListener);

        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);//设置声源
        mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);//设置视频源

        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);//设置音频输出格式为3gp  DEFAULT THREE_GPP
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);//设置音频编码为amr_nb   AMR_NB DEFAULT AAC
        mRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);//录制视频编码 264
        outputPath = cachePath + File.separator + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".mp4";
        mRecorder.setOutputFile(outputPath);
        mRecorder.setVideoSize(width, height);//设置录制视频尺寸     mWidth   mHeight

        mRecorder.setVideoFrameRate(30);//每秒3帧
        mRecorder.setVideoEncodingBitRate(4 * 1024 * 1024);
        mRecorder.setOrientationHint(isNormalNineToSixteen ? 90 : 0);// 输出旋转90度，保持竖屏录制
        mRecorder.setMaxDuration(maxRecordSeconds * 1000);

        mRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());//预览显示的控件
    }

    //开始录制视频
    private boolean startRecord() {
        //录制时显示进度条
        setUiOrientation();

//        initCamera();
        if (mCamera == null) return false;
        mCamera.unlock();
        //是否是1:1的比例
        boolean isOneToOne = (mSurfaceView.getWidth() / mSurfaceView.getHeight() == 1);
        if (isOneToOne) {
//            configMediaRecorder(960,960);
            configMediaRecorder(1280, 720);
        } else {
            configMediaRecorder(1280, 720);
        }
        try {
            //开始录制
            mRecorder.prepare();
            mRecorder.start();
        } catch (Exception e) {
            //摄像头不支持预设的输出宽高则寻找最贴近的摄像头支持的宽高
            configMediaRecorder(videoSize.width, videoSize.height);
            //开始录制
            try {
                mRecorder.prepare();
                mRecorder.start();
            } catch (Exception e1) {
                e1.printStackTrace();
                return false;
            }

        }
        return true;
    }

    //暂停录制视频
    private void pauseRecord() {
    }

    //结束录制视频
    private void stopRecord() {
        // 设置后不会崩
        mRecorder.setOnErrorListener(null);
        mRecorder.setPreviewDisplay(null);
        //停止录制
        try {
            mRecorder.stop();
        } catch (Exception e) {
            mRecorder = null;
            mRecorder = new MediaRecorder();
        }
        mRecorder.reset();
        //释放资源
        mRecorder.release();
        mRecorder = null;
    }

    //结束录制视频 + 其它UI操作
    private void completeStopRecord() {
        if (mStartedFlg) {
            stopRecord();
            if (mCamera != null) {
                mCamera.lock();
            }
            releaseCamera();
        }
        mStartedFlg = false;
        mImgStartRecord.setBackground(VideoRecordActivity.this.getResources().getDrawable(R.mipmap.icon_video_record_enable));
        mTvChoose.setVisibility(View.VISIBLE);
        mTvReRecord.setVisibility(View.VISIBLE);
        mImgStartRecord.setEnabled(false);
        timeHandler.removeCallbacks(timeRunnable);
    }

    //点击返回时对资源进行释放
    private void releaseRecordAndCamera() {
        if (mStartedFlg) {
            stopRecord();
            mCamera.lock();
            releaseCamera();
        }
        mStartedFlg = false;
    }

    //重置进度
    private void resetProgress() {
        if (recordProgress.getVisibility() == View.VISIBLE) {
            recordProgress.resetProgress();
            recordProgress.setVisibility(View.GONE);
        }
        if (verticalRecordProgress.getVisibility() == View.VISIBLE) {
            verticalRecordProgress.resetProgress();
            verticalRecordProgress.setVisibility(View.GONE);
        }
        recordSeconds = -1;
    }

    //释放摄像头资源
    private void releaseCamera() {
        if (mCamera != null) {
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
    }

    //通过对比得到与宽高比最接近的预览尺寸（如果有相同尺寸，优先选择）
    public Camera.Size getCloselyPreSize(boolean isPortrait, int surfaceWidth, int surfaceHeight, List<Camera.Size> preSizeList) {
        if (preSizeList != null && preSizeList.size() > 0) {
            //机型适配 有些机型获取的preSizeList顺序是从小到大的
            if (preSizeList.get(preSizeList.size() - 1).width > preSizeList.get(0).width) {
                Collections.reverse(preSizeList);
            }
        }

        int reqTmpWidth;
        int reqTmpHeight;
        // 当屏幕为垂直的时候需要把宽高值进行调换，保证宽大于高
        if (isPortrait) {
            reqTmpWidth = surfaceHeight;
            reqTmpHeight = surfaceWidth;
        } else {
            reqTmpWidth = surfaceWidth;
            reqTmpHeight = surfaceHeight;
        }
        //先查找preview中是否存在与SurfaceView相同宽高的尺寸
        for (Camera.Size size : preSizeList) {
            if ((size.width == reqTmpWidth) && (size.height == reqTmpHeight)) {
                return size;
            }
        }

        // 得到与传入的宽高比最接近的size
        float reqRatio = ((float) reqTmpWidth) / reqTmpHeight;
        float curRatio, deltaRatio;
        float deltaRatioMin = Float.MAX_VALUE;
        Camera.Size retSize = null;
        for (Camera.Size size : preSizeList) {
            curRatio = ((float) size.width) / size.height;
            deltaRatio = Math.abs(reqRatio - curRatio);
            if (deltaRatio < deltaRatioMin) {
                deltaRatioMin = deltaRatio;
                retSize = size;
            }
        }

        return retSize;
    }

    //通过对比得到与编码尺寸最相近 摄像头支持的输出比例
    public Camera.Size getCloselyVideoSize(boolean isPortrait, int surfaceWidth, int surfaceHeight, List<Camera.Size> videoSizeList) {
        if (videoSizeList != null && videoSizeList.size() > 0) {
            //机型适配 有些机型获取的preSizeList顺序是从小到大的
            if (videoSizeList.get(videoSizeList.size() - 1).width > videoSizeList.get(0).width) {
                Collections.reverse(videoSizeList);
            }
        }

        int reqTmpWidth;
        int reqTmpHeight;
        // 当屏幕为垂直的时候需要把宽高值进行调换，保证宽大于高
        if (isPortrait) {
            reqTmpWidth = surfaceHeight;
            reqTmpHeight = surfaceWidth;
        } else {
            reqTmpWidth = surfaceWidth;
            reqTmpHeight = surfaceHeight;
        }
        //先查找preview中是否存在与SurfaceView相同宽高的尺寸
        for (Camera.Size size : videoSizeList) {
            if ((size.width == reqTmpWidth) && (size.height == reqTmpHeight)) {
                return size;
            }
        }

        // 得到与传入的宽高比最接近的size
        float reqRatio = ((float) reqTmpWidth) / reqTmpHeight;
        float curRatio, deltaRatio;
        float deltaRatioMin = Float.MAX_VALUE;
        Camera.Size retSize = null;
        for (Camera.Size size : videoSizeList) {
            curRatio = ((float) size.width) / size.height;
            deltaRatio = Math.abs(reqRatio - curRatio);
            if (deltaRatio < deltaRatioMin) {
                deltaRatioMin = deltaRatio;
                retSize = size;
            }
        }
        return retSize;
    }

    //获取摄像头支持的输出比例 第二相近的分辨率中 最大的分辨率 暂时不可用
    //因为预览的视频比例是正方形 这里设置第二时 预览视频页面会有拉伸
    public Camera.Size getCloselyVideoSizeMoreClear(boolean isPortrait, int surfaceWidth, int surfaceHeight, List<Camera.Size> videoSizeList) {
        if (videoSizeList != null && videoSizeList.size() > 0) {
            //机型适配 有些机型获取的preSizeList顺序是从小到大的
            if (videoSizeList.get(videoSizeList.size() - 1).width > videoSizeList.get(0).width) {
                Collections.reverse(videoSizeList);
            }
        }

        int reqTmpWidth;
        int reqTmpHeight;
        // 当屏幕为垂直的时候需要把宽高值进行调换，保证宽大于高
        if (isPortrait) {
            reqTmpWidth = surfaceHeight;
            reqTmpHeight = surfaceWidth;
        } else {
            reqTmpWidth = surfaceWidth;
            reqTmpHeight = surfaceHeight;
        }
        //先查找preview中是否存在与SurfaceView相同宽高的尺寸
        for (Camera.Size size : videoSizeList) {
            if ((size.width == reqTmpWidth) && (size.height == reqTmpHeight)) {
                return size;
            }
        }

        // 得到与传入的宽高比最接近的size
        float reqRatio = ((float) reqTmpWidth) / reqTmpHeight;

        //对支持的分辨率进行分组
        Map<Float, List<Camera.Size>> sizeMap = new TreeMap<>(
                new Comparator<Float>() {
                    @Override
                    public int compare(Float o1, Float o2) {
                        return o2.compareTo(o1);
                    }
                }
        );
        for (Camera.Size size : videoSizeList) {
            List<Camera.Size> tempList = sizeMap.get(((float) size.width) / size.height);
            //如果取不到数据,那么直接new一个空的ArrayList
            if (tempList == null) {
                tempList = new ArrayList<>();
                tempList.add(size);
                sizeMap.put(((float) size.width) / size.height, tempList);
            } else {
                //某个sku之前已经存放过了,则直接追加数据到原来的List里
                tempList.add(size);
            }
        }

        //用list进行保存 方便寻找下标
        List<CameraSizeBean> floatSizeList = new ArrayList<>();
        for (Float scale : sizeMap.keySet()) {
            CameraSizeBean cameraSizeBean = new CameraSizeBean();
            cameraSizeBean.scale = scale;
            cameraSizeBean.sizes = sizeMap.get(scale);
            floatSizeList.add(cameraSizeBean);
        }

        float curRatio, deltaRatio;
        float deltaRatioMin = Float.MAX_VALUE;
        Camera.Size retSize = null;
        for (Camera.Size size : videoSizeList) {
            curRatio = ((float) size.width) / size.height;
            deltaRatio = Math.abs(reqRatio - curRatio);
            if (deltaRatio < deltaRatioMin) {
                deltaRatioMin = deltaRatio;
                retSize = size;
            }
        }
        float mScale = 0;
        for (Float scale : sizeMap.keySet()) {
            for (int i = 0; i < sizeMap.get(scale).size(); i++) {
                if (retSize.width == sizeMap.get(scale).get(i).width && retSize.height == sizeMap.get(scale).get(i).height) {
                    mScale = scale;
                    break;
                }
            }
        }

        int index = 0;
        for (int i = 0; i < floatSizeList.size(); i++) {
            if (mScale == floatSizeList.get(i).scale) {
                index = i;
                break;
            }
        }

        retSize = floatSizeList.get(index - 1).sizes.get(0);
        return retSize;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timeHandler.removeCallbacks(timeRunnable);
    }

    @Override
    public void onBackPressed() {
        releaseRecordAndCamera();
        super.onBackPressed();
    }

    @Override
    public void loadSucceed(String result) {
    }

    @Override
    public void loadFaild(String error) {
    }
}
